<script setup lang="ts">
import dayjs from "dayjs";
import duration from "dayjs/plugin/duration";

dayjs.extend(duration);

const timeOutStore = useMyTimeoutStore();

const remainingTimeVM = shallowRef<duration.Duration | undefined>(undefined);
let interval: number | undefined;
const CleanTimeOut = () => {
  window.clearInterval(interval);
};
const startTime = dayjs();

const watchStopHandler = watch(() => timeOutStore.timeOutSec, (newVal, oldValue) => {
  if (newVal !== 0 && oldValue === 0) {
    // 计算结束时间
    const endTime = startTime.add(timeOutStore.timeOutSec, "second");
    timeOutStore.setNowTime(endTime.diff(dayjs(), "second"));
    interval = window.setInterval(doInterval, 1000); 
    watchStopHandler()
  }
})
function doInterval() {
  if (!timeOutStore.nowTime) 
    return;
  if (timeOutStore.nowTime <= 0) {
    timeOutStore.nowTime = 0
    CleanTimeOut();
    timeOutStore.cb?.()
  }
  else {
    remainingTimeVM.value = dayjs.duration(
      timeOutStore.nowTime * 1000,
    );
  }
  timeOutStore.setNowTime(timeOutStore.nowTime - 1);
};

onUnmounted(() => {
  CleanTimeOut();
  timeOutStore.$reset();
  console.log("fin. unmount TimeCountOut.vue");
});

const timeView = computed(() => {
  return `${remainingTimeVM.value?.hours()}小时 ${remainingTimeVM.value?.minutes()}分钟 ${remainingTimeVM.value?.seconds()}秒`;
});
</script>

<template>
  <div v-if="remainingTimeVM" class="h-12 text-red-500">
    <p>剩余时间:</p>
    <p>
      {{ timeView }}
    </p>
  </div>
</template>
